package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.entity.CameraData;
import edu.ynu.se.xiecheng.achitectureclass.service.CameraDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

@Api(tags = "摄像头数据接口")
@RestController
@RequestMapping("/api/camera-data")
@RequiredArgsConstructor
public class CameraDataController {
    private final CameraDataService cameraDataService;

    @ApiOperation("获取最近的摄像头抓拍图片")
    @GetMapping("/recent")
    public ResponseEntity<List<CameraData>> getRecentPhotos(
            @RequestParam Long deviceId,
            @RequestParam(defaultValue = "10") int limit) {
        return ResponseEntity.ok(cameraDataService.findRecentPhotos(deviceId, limit));
    }

    @ApiOperation("手动触发摄像头抓拍")
    @PostMapping("/collect")
    public ResponseEntity<Void> collectCameraData() {
        cameraDataService.collectCameraData();
        return ResponseEntity.ok().build();
    }

    @ApiOperation("获取摄像头访问令牌")
    @GetMapping("/token")
    public ResponseEntity<Map<String, String>> getCameraToken() {
        String token = cameraDataService.ensureCameraToken();
        Map<String, String> response = new HashMap<>();
        response.put("accessToken", token);
        return ResponseEntity.ok(response);
    }

    @ApiOperation("获取历史抓拍记录")
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getCaptureHistory(
            @RequestParam(required = false) Long startTime,
            @RequestParam(required = false) Long endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        Date start = startTime != null ? new Date(startTime) : null;
        Date end = endTime != null ? new Date(endTime) : null;
        
        List<CameraData> photos = cameraDataService.findPhotosByTimeRange(start, end, pageNum, pageSize);
        long total = cameraDataService.countPhotosByTimeRange(start, end);
        
        Map<String, Object> response = new HashMap<>();
        response.put("data", photos);
        response.put("total", total);
        
        return ResponseEntity.ok(response);
    }
}